import ajax from "../../../until/request.js"

import { top } from '../../public/js/public.js'

class InCar {

  constructor() {
    this.getDoms()
    this.searchValue()
    this.getGoodId()
    top()
  }
  getDoms () {
    // 获取渲染父元素
    this.clickItem = document.querySelector(".clickItem")
    // this.goods_infos = JSON.parse(localStorage.getItem('goods_infos')) || []
    // this.goods_infos = []

    // 获取token
    this.token = localStorage.getItem('token')
    // 获取用户id
    this.userId = localStorage.getItem('user_id')
    // 获取搜索框
    this.search = document.querySelector("#search")
    this.searchBtn = document.querySelector("#searchBtn")

    // 获取 userInfo
    this.userInfo = JSON.parse(localStorage.getItem("userInfo"))
  }
  //  取出 商品的id
  getGoodId () {
    console.log(this.userInfo.good_id)
    ajax.getPro({
      url: 'http://localhost:8888/goods/item',
      params: {
        id: this.userInfo.good_id
      },
    }).then(res => {
      let data = JSON.parse(res)
      inCar.renderMagnifier(data.info)
    })
  }
  // 渲染放大镜 
  renderMagnifier (magnifier) {
    // console.log(magnifier)
    // 渲染放大镜结构
    const { goods_id, title, img_big_logo, current_price, price, goods_introduce, goods_number } = magnifier
    //  渲染数据
    this.clickItem.innerHTML =
      ` 
     <div class="mid_box ">
          <img src="${img_big_logo}" alt="" class="image"  >
          <div class="layer"></div>   
        </div>
      
        <div class="big_box" id="bigBox"> <img src="${img_big_logo}" alt=""> </div>
         <div class="desc">
          <h3>${title}</h3>
          <div class="current_price">¥${current_price} <span class="price">${price}</span> </div>
          <div class="mask">
            <dl>
              <dt>促销</dt>
              <dd>12月好物放送，App领券购买直降120元</dd>
            </dl>
            <dl>
              <dt>配送</dt>
              <dd>至近自营店送货</dd>
            </dl>
            <dl>
              <dt>服务</dt>
              <dd><span>无忧退货</span><span>快速退款</span><span>免费包邮</span><a href="javascript:;">了解详情</a></dd>
            </dl>
          </div>
          <div class="num">
            数量:<button type="button" class="btn btn-light sub" data-id="${goods_id}">-</button>
            <input type="text" value="1" class="cart_number" disabled="true" data-id="${goods_id}">
            <button type="button" class="btn btn-light add"   data-id="${goods_id}">+</button>
            <span class="numbers">库存: <span>${goods_number}</span> </span>
          </div>
          <button type="button" class="btn btn-success inCar" data-id="${goods_id}" >加入购物车</button>
        </div>
        <div class="similarRec"> </div>
        <div class="goods_introduce">${goods_introduce}</div> 
    `
    // 放大效果  事件委托
    this.similarRec = this.clickItem.querySelector(".similarRec")
    inCar.magnifying()
    //  car 
    // console.log(this)
    this.inCar = this.clickItem.querySelector(".inCar")
    this.cart_number = this.clickItem.querySelector(".cart_number")
    this.sub = this.clickItem.querySelector(".sub")
    this.add = this.clickItem.querySelector(".add")
    this.inventory = this.clickItem.querySelector(".numbers span")
    inCar.inShoppingCar()
    // 取 精彩推荐的商品
    let similarData = ajax.getPro({
      url: 'http://localhost:8888/goods/list',
      params: {
        pagesize: 300, // 每页多少条数据
      }
    })
    similarData.then(res => {
      inCar.renderSimilarData(JSON.parse(res).list)
    })



  }
  //放大镜
  magnifying () {
    let big_box = document.querySelector(".big_box")
    let layer = document.querySelector(".layer")
    let img = document.querySelector(".image")
    let timer = null
    let mid_box = document.querySelector("mid_box")
    //  this.clickItem 设置 鼠标 进入 big_box 显示   出去 big_box 隐藏
    img.addEventListener("mouseenter", function () {
      clearTimeout(timer)
      big_box.style.display = "block"
      layer.style.display = "block"
    })
    layer.addEventListener("mouseenter", function () {
      clearTimeout(timer)
      big_box.style.display = "block"
      layer.style.display = "block"
    })
    layer.addEventListener("mouseleave", function () {
      timer = setTimeout(() => {
        big_box.style.display = "none"
        layer.style.display = "none"
      }, 300)
    })
    // 延时隐藏
    img.addEventListener("mouseleave", function () {
      timer = setTimeout(() => {
        big_box.style.display = "none"
        layer.style.display = "none"
      }, 300)
    })

    this.clickItem.addEventListener('mousemove', e => {

      // 鼠标在页面中的位置 e.pageX
      // 盒子的位置  .getBoundingClientRect()  left right top bottom
      // 鼠标在盒子中的位置
      let x = e.pageX - this.clickItem.getBoundingClientRect().left

      let y =
        e.pageY -
        this.clickItem.getBoundingClientRect().top -
        document.documentElement.scrollTop

      // 让黑色遮罩层跟着动
      if (x >= 0 && x <= 400 && y >= 0 && y <= 400) {
        let mx = 0
        let my = 0
        if (x < 100) mx = 0
        if (x >= 100 && x <= 300) mx = x - 100
        if (x > 300) mx = 200
        layer.style.left = mx + "px"
        if (y < 100) my = 0
        if (y >= 100 && y <= 300) my = y - 100
        if (y > 300) my = 200
        layer.style.top = my + "px"

        //  大图的移动距离  =   遮罩层移动距离 / 遮罩层的可移动距离  * 大图的宽度

        // 给大图进行赋值操作 
        big_box.children[0].style.left = -(mx / (img.offsetWidth - layer.offsetWidth)) * big_box.offsetWidth + "px"
        big_box.children[0].style.top = -(my / (img.offsetWidth - layer.offsetWidth)) * big_box.offsetWidth + "px"
      }
    })
  }
  // 渲染 精彩推荐数据
  renderSimilarData (similarData) {
    // 获取数据
    let similar_data = similarData.filter(item => item.is_hot == true)
    // 随机
    function getRandomElements (array, numElements) {
      const shuffledArray = array.sort(() => Math.random() - 0.5)
      return shuffledArray.slice(0, numElements)
    }

    similar_data = getRandomElements(similar_data, 5)
    // console.log(this.clickItem.querySelector(".similarRec"))
    let h4 = document.createElement("h4")
    let box_panel = document.createElement("div")

    h4.innerText = "精彩推荐"
    box_panel.className = "box-panel"

    this.similarRec.append(h4)
    this.similarRec.append(box_panel)
    // 渲染数据   map  join

    let box_items = similar_data.map(item => {
      return `
      <a class="box-item" href="./hot_rmd.html" data-id="${item.goods_id}" >
      ${item.is_hot ? '<div class="is_hot">热门</div>' : ""}
      ${item.is_sale ? `<div class="is_sale">${item.sale_type}</div>` : ""}
      <img src=${item.imgSmall_logo} alt="">
      <div class="title">${item.title}</div>
      <div class="current_price">¥${item.current_price} &nbsp;<span class="price">${item.price}</span> </div>
      </a>`
    })

    box_panel.innerHTML = box_items.join("")
    box_panel.addEventListener("click", e => {
      const boxItem = e.target.closest('.box-item')
      if (boxItem) {
        this.userInfo.good_id = boxItem.dataset.id
        localStorage.setItem("userInfo", JSON.stringify(this.userInfo))
        this.getGoodId()
      }
    })

  }
  // inShoppingCar  加入购物车
  inShoppingCar () {
    // 加
    this.add.onclick = () => {
      let num = this.cart_number.value
      if (num >= Number(this.inventory.innerText)) return
      num++
      this.cart_number.value = num
    }
    // 减
    this.sub.onclick = () => {
      let num = this.cart_number.value
      if (num <= 1) return
      num--
      this.cart_number.value = num
    }
    // 加入购物车
    this.inCar.onclick = (e) => {
      e.preventDefault()

      if (this.userInfo.user_id == null) {
        alert("请先登录")
        return
      } else {
        let num = this.cart_number.value
        // 发送请求 加入购物车
        ajax.postProToken({
          url: "http://localhost:8888/cart/add",
          params: {
            id: this.userInfo.user_id,
            goodsId: this.userInfo.good_id,
            token: this.userInfo.token
          }
        }).then(res => {
          // console.log(res)
        })
        // 发送请求 修改商品数量 
        ajax.postProToken({
          url: "http://localhost:8888/cart/number",
          params: {
            id: this.userInfo.user_id,
            goodsId: this.userInfo.good_id,
            token: this.userInfo.token,
            number: num - 0,

          }
        }).then(res => {
          // console.log(res)
        })
        location.href = "../cart/shoppcar.html"
      }
    }
  }

  //搜索功能
  searchValue () {
    this.searchBtn.addEventListener("click", (e) => {
      e.preventDefault()

      // console.log(searchValue)
      if (this.userInfo.user_id && this.search.value) {
        sessionStorage.setItem("search_value", this.search.value)
        // 跳转到搜索页
        location.href = "../search/search.html"
      } else {
        alert("请先登录")
        return
      }
    })

    this.search.addEventListener("keydown", (e) => {
      e.preventDefault()
      // 判断按下的键是否是回车键
      if (e.keyCode === 13) {
        if (this.userInfo.user_id && this.search.value) {
          sessionStorage.setItem("search_value", this.search.value)
          // 跳转到搜索页
          location.href = "../search/search.html"
        } else {
          console.log(1)
          alert("请先登录")
          return
        }
      }
    })
  }
}
let inCar = new InCar()

export default inCar